<?php

class Sistema_AmbientesController extends App_Controller_Action
{
    private $_table     = 'AMBIENTES';
    private $_pk        = 'AMB_ID';
    private $_order_col = 'AMB_ORD';
    private $_order     = 'ASC';
    private $_sta_col   = 'AMB_STA';
    private $obj        = '';
    private $form       = '';
    private $_file_col  = 'AMB_FILE'; 
    public  $dir        = 'public/upload/ambientes/';
    
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Sistema_Form_Ambientes();        
    }

    public function indexAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        $where = $this->_pk.' > 0';
        
        $dscfiltro = trim($this->_getParam('dscfiltro', ''));
        
        if($dscfiltro != '') $where .= ' AND AMB_NOM like "%'.$dscfiltro.'%"';
        
        $this->view->dscfiltro = $dscfiltro;
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result,20);
        
    }
       
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_form_pdr.js');
       
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_ambientes.js?1='.rand(9,9999)); 
        
        Zend_Loader::loadClass('imagem','library');
        
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    $returnImg = imagem::upload($this->_file_col,$this->dir,$id.'_grd');
                    
                    $data = $this->form->getValues();
                    
                    unset($data['Salvar']);
                    unset($data[$this->_file_col]);
                    unset($data['img']);
                    
                    unset($data['FOR_ID']);
                    unset($data['FOR_IDS']);
                    unset($data['LIN_ID']);
                    unset($data['LIN_IDS']);
                    unset($data['COR_ID']);
                    unset($data['COR_IDS']);
                    unset($data['ACA_ID']);
                    unset($data['ACA_IDS']);

                    //$this->db->beginTransaction();
                    if($id == 0){
                        $this->db->insert($this->_table, $data);
                        $id =  $this->db->lastInsertId();   
                        
                        imagem::rename($id.'_grd',$this->dir,$returnImg['filenew']);
                    }
                    else {
                        $this->db->update($this->_table, $data,$this->_pk.' = ' . $id);
                    }
                    
                    // fornecedores
                    $this->db->delete('AMBIENTES_FORNECEDOR',$this->_pk.' = ' . $id);
                    foreach($formData['FOR_ID'] as $for) {
                        $ins = array( 'AMB_ID' => $id, 'FOR_ID' => $for );
                        $this->db->insert('AMBIENTES_FORNECEDOR', $ins);
                    }
                    
                    // linhas
                    $this->db->delete('AMBIENTES_LINHA',$this->_pk.' = ' . $id);
                    foreach($formData['LIN_ID'] as $for) {
                        $ins = array( 'AMB_ID' => $id, 'LIN_ID' => $for );
                        $this->db->insert('AMBIENTES_LINHA', $ins);
                    }
                    
                    // cores
                    $this->db->delete('AMBIENTES_CORES',$this->_pk.' = ' . $id);
                    foreach($formData['COR_ID'] as $for) {
                        $ins = array( 'AMB_ID' => $id, 'COR_ID' => $for );
                        $this->db->insert('AMBIENTES_CORES', $ins);
                    }
                    
                    // acabamentos
                    $this->db->delete('AMBIENTES_ACABAMENTOS',$this->_pk.' = ' . $id);
                    foreach($formData['ACA_ID'] as $for) {
                        $ins = array( 'AMB_ID' => $id, 'ACA_ID' => $for );
                        $this->db->insert('AMBIENTES_ACABAMENTOS', $ins);
                    }

                    // redimencionar
                    if(strlen($_FILES[$this->_file_col]['tmp_name']) > 1){
                        $img = glob($this->dir.$id.'_grd.*');
                        foreach($img as $filetemp) $filename = $filetemp; // 1920 x 1080
                        
                        imagem::reizeFull($filename, str_replace('_grd.','_grd_lst.',$filename), '960', '540');
                        
                        imagem::reizeFull($filename, str_replace('_grd.','.',$filename), '1366', '768');
                        imagem::reizeFull($filename, str_replace('_grd.','_lst.',$filename), '500', '222');
                        imagem::reizeFull($filename, str_replace('_grd.','_crs.',$filename), '180', '120');
                        
                    }
                    
                    
                    $sessao = new Zend_Session_Namespace('Ambientes');
                    unset($sessao->ambientes);
                    
                    
                    //$this->db->commit();
                    
                    $this->_helper->redirector('index');
                    
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                //$this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->db->fetchRow('SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id);
                $this->form->populate($data);
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        if((int) $id > 0 ) {   
            $this->db->beginTransaction();
            try {
                $ok = (bool) $this->db->delete($this->_table, $this->_pk . ' = ' . $id);
                
                Zend_Loader::loadClass('imagem','library');
                imagem::delete($id,$this->dir,TRUE);
            
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = MSG_DELETE;
                $this->db->rollBack();
            }             
        }       
        echo json_encode(array('ok' => $ok, 'msg'=> $msg));
        //$this->_helper->redirector('index');
    }
    
    public function linhasAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $html = '';
        $AMB_ID= $this->_getParam('AMB_ID', 0);
        $FOR_ID = $this->_getParam('FOR_ID', 0);
        
        if(is_array($FOR_ID)) {   
            $ok = TRUE;
            
            $arr_set = array();
            
            $query = 'SELECT SQL_CACHE LIN_ID FROM AMBIENTES_LINHA WHERE AMB_ID = '.$AMB_ID;
            $result = $this->db->fetchAll($query);
            foreach($result as $row) $arr_set[$row['LIN_ID']] = $row['LIN_ID'];

            $list = implode(',', array_values($FOR_ID)); 
            
            $html = '<select id="LIN_ID" name="LIN_ID[]" class="chosen-select" multiple="multiple" style="width:500px;">';
            
            $query = 'SELECT SQL_CACHE LIN_ID,LIN_NOM FROM LINHA WHERE LIN_STA = 1 AND FOR_ID in('.$list.') ORDER BY LIN_NOM ASC';
            $result = $this->db->fetchAll($query);
            foreach($result as $row){  
                $selected = array_search($row['LIN_ID'], $arr_set) > '' ? 'selected=""':'';            
                $html .= '<option '.$selected.' value="'.$row['LIN_ID'].'">'.$row['LIN_NOM'].'</option>'; 
            }
            $html .= '</select><br><br>'.$links.'<script>$(function(){ $(".chosen-select").chosen(); }); </script>';
            
        }
        
        echo json_encode(array('ok' => $ok, 'html'=> $html));
    }
    
    public function coresAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $html = '';
        $AMB_ID= $this->_getParam('AMB_ID', 0);
        $LIN_ID = $this->_getParam('LIN_ID', 0);
        
        if(is_array($LIN_ID)) {   
            $ok = TRUE;
            
            $arr_set = array();
            
            $query = 'SELECT SQL_CACHE COR_ID FROM AMBIENTES_CORES WHERE AMB_ID = '.$AMB_ID;
            $result = $this->db->fetchAll($query);
            foreach($result as $row) $arr_set[$row['COR_ID']] = $row['COR_ID'];

            $list = implode(',', array_values($LIN_ID)); 
            
            $html = '<select id="COR_ID" name="COR_ID[]" class="chosen-select" multiple="multiple" style="width:500px;">';
            
            $query = 'SELECT SQL_CACHE COR_ID,COR_NOM FROM CORES WHERE COR_STA = 1 AND LIN_ID in('.$list.') ORDER BY COR_NOM ASC';
            $result = $this->db->fetchAll($query);
            foreach($result as $row){  
                $selected = array_search($row['COR_ID'], $arr_set) > '' ? 'selected=""':'';            
                $html .= '<option '.$selected.' value="'.$row['COR_ID'].'">'.$row['COR_NOM'].'</option>'; 
            }
            $html .= '</select><br><br>'.$links.'<script>$(function(){ $(".chosen-select").chosen(); }); </script>';
            
        }
        
        echo json_encode(array('ok' => $ok, 'html'=> $html));
    }
    
    public function acabamentosAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $html = '';
        $AMB_ID= $this->_getParam('AMB_ID', 0);
        $LIN_ID = $this->_getParam('LIN_ID', 0);
        
        if(is_array($LIN_ID)) {   
            $ok = TRUE;
            
            $arr_set = array();
            
            $query = 'SELECT SQL_CACHE ACA_ID FROM AMBIENTES_ACABAMENTOS WHERE AMB_ID = '.$AMB_ID;
            $result = $this->db->fetchAll($query);
            foreach($result as $row) $arr_set[$row['ACA_ID']] = $row['ACA_ID'];

            $list = implode(',', array_values($LIN_ID)); 
            
            $html = '<select id="ACA_ID" name="ACA_ID[]" class="chosen-select" multiple="multiple" style="width:500px;">';
            
            $query = 'SELECT SQL_CACHE ACA_ID,ACA_NOM FROM ACABAMENTOS WHERE ACA_STA = 1 AND LIN_ID in('.$list.') ORDER BY ACA_NOM ASC';
            $result = $this->db->fetchAll($query);
            foreach($result as $row){  
                $selected = array_search($row['ACA_ID'], $arr_set) > '' ? 'selected=""':'';            
                $html .= '<option '.$selected.' value="'.$row['ACA_ID'].'">'.$row['ACA_NOM'].'</option>'; 
            }
            $html .= '</select><br><br>'.$links.'<script>$(function(){ $(".chosen-select").chosen(); }); </script>';
            
        }
        
        echo json_encode(array('ok' => $ok, 'html'=> $html));
    }
    
}